<template>
  <el-dialog
      :title="form.tripId ? '行程单详情' : '新增行程单'"
      width="900px"
      v-model="visible"
      :close-on-click-modal="false"
      draggable
  >
    <el-form
        ref="dataFormRef"
        :model="form"
        :rules="dataRules"
        label-width="90px"
        v-loading="loading"
        inline
        class="red-label-form"
        :disabled="isDetail"
    >
      <div class="form-row">
        <!-- 第一行：咨询号、客户姓名、手机号 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="咨询号" prop="inquireNumber">
              <!-- 详情模式（有tripId）：显示input -->
              <el-input
                  v-if="form.tripId"
                  v-model="form.inquireNumber"
                  placeholder="咨询号"
                  disabled
                  :disabled="isDetail"
              ></el-input>
              <!-- 新增模式（无tripId）：显示下拉框 -->
              <el-select
                  v-else
                  v-model="form.inquireId"
                  placeholder="选择咨询"
                  clearable
                  @change="handleInquireChange"
              >
                <el-option
                    v-for="item in inquireList"
                    :key="item.inquireId"
                    :label="item.inquireNumber"
                    :value="item.inquireId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="客户姓名" prop="cusName">
              <el-input
                  v-model="form.cusName"
                  placeholder="请输入客户姓名"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="手机号" prop="cusTel">
              <el-input
                  v-model="form.cusTel"
                  placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：出行人数、意向目的地、预算 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="出行人数" prop="countPerson">
              <el-input
                  v-model="form.countPerson"
                  placeholder="请输入出行人数"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="意向目的地" prop="intendedDest">
              <el-input
                  v-model="form.intendedDest"
                  placeholder="请输入意向目的地"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="预算" prop="money">
              <el-input
                  v-model="form.money"
                  placeholder="请输入预算"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：预计出发时间、可调整时间、出行天数 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="预计出发时间" prop="goTime">
              <el-input
                  v-model="form.goTime"
                  placeholder="请输入预计出发时间"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="可调整时间" prop="adjustTime">
              <el-input
                  v-model="form.adjustTime"
                  placeholder="请输入可调整时间"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="出行天数" prop="planDays">
              <el-input
                  v-model="form.planDays"
                  placeholder="请输入出行天数"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 备注 -->
      <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 15px;">
        <span>备注：</span>
        <textarea
            v-model="remarkContent"
            rows="3"
            placeholder="请输入"
            style="flex: 1; padding: 6px; border: 1px solid #ddd; border-radius: 4px;"
            :disabled="isDetail"
        ></textarea>
      </div>

      <!-- 费用相关总计 -->
      <el-row :gutter="10" class="money-row">
        <el-col :span="10">
          <el-form-item label="旅行费用合计" prop="tripCosts" class="money-item">
            <el-input v-model="form.tripCosts"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="服务费用合计" prop="serviceFee" class="money-item">
            <el-input v-model="form.serviceFee"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="money-row">
        <el-col :span="12">
          <el-form-item label="费用总计" prop="totalCost" class="money-item">
            <el-input v-model="form.totalCost"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 动态内容块容器 -->
      <div
          v-for="(item, index) in contentItems"
          :key="index"
          class="content-block"
      >
        <span>内容{{ index + 1 }}</span>
        <!-- 时间段选择 -->
        <div>
          <span>时间段</span>
          <el-form-item
              :prop="`contentItems[${index}].startTime`"
              :rules="contentRules.startTime"
              label-width="0"
          >
            <el-date-picker
                v-model="item.startTime"
                type="date"
                placeholder="选择开始时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="w-full"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
              :prop="`contentItems[${index}].endTime`"
              :rules="contentRules.endTime"
              label-width="0"
          >
            <el-date-picker
                v-model="item.endTime"
                type="date"
                placeholder="选择结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="w-full"
            ></el-date-picker>
          </el-form-item>
          <el-button
              type="danger"
              :disabled="loading || contentItems.length <= 1"
              @click="handleDeleteBlock(index)"
          >
            删除内容
          </el-button>
        </div>


        <!-- 内容备注 -->
        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 15px;">
          <span>内容：</span>
          <textarea
              v-model="item.remark"
              rows="3"
              placeholder="请输入"
              style="flex: 1; padding: 6px; border: 1px solid #ddd; border-radius: 4px;"
              :disabled="isDetail"
          ></textarea>
        </div>

        <!-- 图片上传 -->
        <div style="display: flex; align-items: flex-start; gap: 8px; margin-bottom: 15px;">
          <span>上传图片：</span>
          <div style="flex: 1;">
            <ImageUpload
                v-model:imageUrl="item.images"
                borderRadius="0%"
                multiple
                @success="(response) => handleImageUploadSuccess(index, response)"
                @error="handleUploadError"
            >
              <template #empty>
                <el-icon><Plus/></el-icon>
              </template>
            </ImageUpload>
          </div>
        </div>

        <!-- 费用相关 -->
        <el-row :gutter="10" class="money-row">
          <el-col :span="11">
            <el-form-item
                label="旅行费用"
                :prop="`contentItems[${index}].tripCost`"
                :rules="contentRules.tripCost"
                class="money-item"
            >
              <el-input v-model="item.tripCost" placeholder="旅行费用" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
                label="服务费用"
                :prop="`contentItems[${index}].serviceFee`"
                :rules="contentRules.serviceFee"
                class="money-item"
            >
              <el-input v-model="item.serviceFee" placeholder="服务费用" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 15px;">
          <span>费用说明：</span>
          <textarea
              v-model="item.costRemark"
              rows="3"
              style="flex: 1; padding: 6px; border: 1px solid #ddd; border-radius: 4px;"
              :disabled="isDetail"
          ></textarea>
        </div>
      </div>

      <!-- 添加内容按钮 -->
      <el-button
          type="primary"
          :disabled="loading"
          @click="handleAddBlock"
          style="float:right;"
      >
        添加内容
      </el-button>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
            type="primary"
            @click="onSubmit"
            :disabled="loading"

        >
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="systemPostDialog">
import { ref, reactive, defineEmits, defineAsyncComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useMessage } from '/@/hooks/message';
import { getInquireBYId, unUseInquireNum, addTrip ,getInquireByTripId,updateTripAmount} from '/@/api/trip/trip';
import {addTripContent,selectByTripId,deleteTripContent,updateTripContent} from '/@/api/trip/tripContent';
import { Plus } from '@element-plus/icons-vue';
import { debounce } from 'lodash'; // 引入防抖函数时
// 定义事件
const emit = defineEmits(['refresh']);

// 响应式变量
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const inquireList = ref([]);
const remarkContent = ref('');
const ImageUpload = defineAsyncComponent(() => import('/@/components/Upload/Image.vue'))
// 新增：控制是否为详情模式（默认false）
const isDetail = ref(false);
//新增：标记是否为编辑模式（默认false）
const isEditMode = ref(false);

// 表单数据
const form = reactive({
  tripId: '',
  inquireNumber: '',
  inquireId: null,
  cusId: '',
  cusTel: '',
  cusName: '',
  countPerson: '',
  intendedDest: '',
  money: '',
  goTime: '',
  adjustTime: '',
  planDays: '',
  tripRemark:'',
  tripCosts: '0',
  serviceFee: '0',
  totalCost: '0',
  delFlag: '',
  createTime: '',
  createBy: '',
  updateTime: '',
  updateBy: '',
  imageUrls: []
});

// 核心：内容块数组，存储多个动态内容块的数据
const contentItems = ref([
  // 初始化一个默认内容块
  {
    startTime: '', // 开始时间
    endTime: '', // 结束时间
    remark: '', // 内容描述
    images: [], // 图片地址数组
    tripCost: '', // 旅行费用
    serviceFee: '', // 服务费用
    costRemark: '' // 费用说明
  }
]);
// 核心：监听内容块旅行费用变化，实时计算合计
watchEffect(() => {
  let totalTripCost = 0;
  let totalServiceFee = 0;
  // 合并遍历，只循环一次
  contentItems.value.forEach(item => {
    const tripCost = Number(item.tripCost) || 0;
    const serviceCost = Number(item.serviceFee) || 0;
    totalTripCost += tripCost;
    totalServiceFee += serviceCost;
  });
  form.tripCosts = totalTripCost.toString();
  form.serviceFee = totalServiceFee.toString();
  form.totalCost = (totalTripCost + totalServiceFee).toString();
});
const contentRules = ref({
  startTime: [{ }],
  endTime: [{}],
  tripCost: [{ }],
  serviceFee: [{ }]

  // startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  // endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  // tripCost: [{ required: true, message: '请输入旅行费用', trigger: 'blur' }],
  // serviceFee: [{ required: true, message: '请输入服务费用', trigger: 'blur' }]
});

// 获取未使用的咨询单
const fetchInquireList = async () => {
  try {
    loading.value = true;
    const res = await unUseInquireNum();
    inquireList.value = res.data || [];
  } catch (err) {
    useMessage().error('获取咨询单失败');
  } finally {
    loading.value = false;
  }
};
const resetEachContentItem = () => {
  contentItems.value.forEach((item, index) => {
    // 重置每个内容块的所有属性为空值
    contentItems.value[index] = {
      remark: '',
      startTime: '',
      endTime: '',
      tripCost: '',
      serviceFee: '',
      costRemark: '',
      images: []
      // 其他字段也设置为空...
    };
  });
};
// 打开弹窗
const openDialog = async (tripId?: string, detailStatus = false) => {
  visible.value = true;
  // 关键：设置详情状态
  isDetail.value = detailStatus;
  form.inquireId = null;
  form.inquireNumber = '';
  form.cusId = '';
  form.cusTel = '';
  form.cusName = '';
  form.countPerson = '';
  form.intendedDest = '';
  form.money = '';
  form.goTime = '';
  form.adjustTime = '';
  form.planDays = '';
  form.tripCosts = '0';
  form.serviceFee = '0';
  //遍历内容块将其设置为空
  resetEachContentItem()
  fetchInquireList();
  if (tripId) {
    // 1. 获取行程单主体信息
    const tripDetail = await getInquireByTripId(tripId);
    const mainData = tripDetail.data;
    console.log(mainData)
    form.inquireNumber = mainData.inquireNumber || '';
    Object.assign(form, mainData);
    remarkContent.value = mainData.remark || '';
    // 2. 获取行程内容块信息
    const contentRes = await selectByTripId(tripId);
    const contentData = contentRes.data || [];

    // 3. 格式化内容块数据
    contentItems.value = contentData.map(item => ({
      id: item.tripContentId, // 关键：将tripContentId映射为id（或直接使用tripContentId）
      tripContentId: item.tripContentId, // 也可以直接保留原字段名
      startTime: item.startTime,
      endTime: item.endTime,
      remark: item.tripContent,
      images: [item.image1, item.image2, item.image3].filter(Boolean),
      tripCost: item.tripCosts?.toString() || '',
      serviceFee: item.serviceFee?.toString() || '',
      costRemark: item.costRemark
    }));
  }
};

// 添加新的内容块
const handleAddBlock = () => {
  contentItems.value.push({
    startTime: '',
    endTime: '',
    remark: '',
    images: [],
    tripCost: '',
    serviceFee: '',
    costRemark: ''
  });
};
// 删除指定内容块
// 在删除方法中使用tripContentId
const handleDeleteBlock = (index: number) => {
  // 从内容块对象中获取tripContentId
  const contentItem = contentItems.value[index];
  const tripContentId = contentItem.tripContentId; // 直接使用原字段名
  // 或者如果之前映射为id了，可以用 contentItem.id

  // 调试用：确认获取到的ID
  console.log('要删除的内容块ID:', tripContentId);

  ElMessageBox.confirm(
      '确定删除当前内容块吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      loading.value = true;

      // 确保ID存在且有效
      if (tripContentId) {
        // 注意：接口需要的是数字类型，这里从接口返回的是字符串，需要转换
        await deleteTripContent(Number(tripContentId));
      }

      contentItems.value.splice(index, 1);
      ElMessage.success('内容块已删除');
    } catch (err) {
      ElMessage.error('删除失败，请重试');
      console.error('删除内容块错误:', err);
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 取消删除
  });
};


// 提交表单
const onSubmit = async () => {
  try {
    // 表单验证
    await dataFormRef.value.validate();

    // 咨询单选择校验
    if (!form.inquireId) {
      ElMessage.warning('请选择咨询单');
      return;
    }

    // 内容块数量校验
    if (contentItems.value.length === 0) {
      ElMessage.warning('请至少添加一个行程内容块');
      return;
    }

    loading.value = true;
    const isEdit = !!form.tripId; // 判断是否为编辑模式
    let newTripId = form.tripId;

    // 1. 保存行程单主体（区分新增和编辑）
    if (isEdit) {
      // 编辑模式：使用更新接口
      const updateRes = await updateTripContent({
        ...form,
        tripRemark: remarkContent.value,
        imageUrls: form.imageUrls
      });
      newTripId = updateRes.data || form.tripId; // 确保tripId有效
    } else {
      // 新增模式：使用新增接口
      const tripRes = await addTrip({
        ...form,
        remark: remarkContent.value,
        imageUrls: form.imageUrls
      });
      newTripId = tripRes.data;
    }

    // 验证tripId有效性
    if (!newTripId) {
      throw new Error(`${isEdit ? '更新' : '新增'}行程单失败，未返回有效tripId`);
    }

    // 组装内容块数据
    const contentItemsData = contentItems.value.map((item, index) => ({
      tripId: newTripId,
      tripContentName: index + 1,
      tripContent: item.remark,
      startTime: item.startTime,
      endTime: item.endTime,
      tripCosts: Number(item.tripCost) || 0,
      serviceFee: Number(item.serviceFee) || 0,
      costRemark: item.costRemark,
      image1: item.images[0] || '',
      image2: item.images[1] || '',
      image3: item.images[2] || '',
      createBy: form.createBy || '当前用户',
      updateBy: form.updateBy || '当前用户'
    }));

    // 3. 批量保存内容块
    if (contentItemsData.length > 0 || !isEdit) {
      const contentResults = await Promise.allSettled(
          contentItemsData.map(content => addTripContent(content))
      );

      // 检查是否有内容块保存失败
      const failedItems = contentResults.filter(
          (result, index) => result.status === 'rejected'
      );

      if (failedItems.length > 0) {
        console.error(`部分内容块保存失败，失败数量: ${failedItems.length}`);
      }
    }
    if (form.tripId) {
      await updateTripAmount({
        tripId: form.tripId,
        tripCosts: Number(form.tripCosts),
        serviceFee: Number(form.serviceFee)
      });
    }
    // 操作成功提示
    ElMessage.success(`${isEdit ? '更新' : '新增'}成功`);
    emit('refresh'); // 通知父组件刷新列表
    visible.value = false; // 关闭弹窗

  } catch (err: any) {
    // 错误处理
    let isEdit;
    ElMessage.error(err.message || `${isEdit ? '更新' : '新增'}失败，请稍后重试`);
    console.error(`${isEdit ? '更新' : '新增'}错误:`, err);
  } finally {
    // 确保加载状态关闭
    loading.value = false;
  }
};
// 处理咨询号选择后回显
const handleInquireChange = async (inquireId: number) => {
  form.cusId='';
  form.inquireNumber = '';
  form.cusId = '';
  form.cusName = '';
  form.cusTel = '';
  form.countPerson = '';
  form.intendedDest = '';
  form.money = '';
  form.goTime = '';
  form.adjustTime = '';
  form.planDays = '';
  form.remark;
  if (inquireId) {
    try {
      loading.value = true;
      const res = await getInquireBYId(inquireId);
      console.log(res.data)
      const detail = res.data;
      form.inquireNumber = detail.inquireNumber;  // 咨询号
      form.cusId = detail.cusId;
      form.cusName = detail.cusName;              // 客户姓名
      form.cusTel = detail.cusTel;                // 手机号
      form.cusId = detail.cusId;
      form.countPerson = detail.countPerson;      // 出行人数
      form.intendedDest = detail.intendedDest;    // 意向目的地
      form.money = detail.money;                  // 预算
      form.goTime = detail.goTime;                // 出发时间
      form.adjustTime = detail.adjustTime;        // 可调整时间
      form.planDays = detail.planDays;            // 出行天数
      form.remark = detail.remark;
    } catch (err) {
      useMessage().error('获取咨询详情失败');
      console.error('回显错误:', err);
    } finally {
      loading.value = false;
    }
  }
};

const handleImageUploadSuccess = (index, response) => {
  if (response.code === 200) {
    contentItems.value[index].images.push(response.data.url);
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败');
  }
};

// 处理图片上传失败
const handleUploadError = (err: any) => {
  ElMessage.error('图片上传失败，请重试');
  console.error('上传错误:', err);
};
// 2. 防抖处理：避免金额频繁变动导致多次请求
const debouncedUpdateAmount = debounce(async () => {
  // 仅在编辑模式（有tripId）且非详情模式下执行更新
  if (!form.tripId || isDetail.value) return;

  try {
    loading.value = true;
    // 构造请求参数（与TripDTO对应）
    const params = {
      tripId: form.tripId,
      tripCosts: Number(form.tripCosts), // 旅行费用合计
      serviceFee: Number(form.serviceFee) // 服务费用合计
    };

    // 调用后端接口，获取更新条数（int类型）
    const updateCount = await updateTripAmount(params);

    // 根据更新条数处理提示
    if (updateCount > 0) {
      console.log(`成功更新${updateCount}条记录`);
      // 可根据需求显示成功提示（建议静默更新，避免频繁弹窗）
      // ElMessage.success('金额已同步更新');
    } else if (updateCount === 0) {
      console.log('无金额变更或记录不存在');
    }
  } catch (err: any) {
    console.error('金额更新失败:', err);
    ElMessage.error('金额同步失败，请重试');
  } finally {
    loading.value = false;
  }
}, 500); // 500ms防抖：用户停止输入后再请求
// 暴露方法
defineExpose({
  openDialog,
});
</script>

<style scoped>
.form-row .el-form-item__label {
  color: red;
  font-weight: normal;
}

textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: vertical;
}

.money-row {
  margin-bottom: 10px;
}

.money-item {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.money-item .el-form-item__label {
  color: black !important;
  white-space: nowrap;
  width: auto;
  padding-right: 5px;
}

.money-item .el-form-item__content {
  margin-left: 8px !important;
}

.upload-demo {
  width: 100%;
  min-height: 100px; /* 增加最小高度，确保可点击区域 */
}
.content-block {
  border: 1px solid plum;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.content-block + .el-button {
  margin-top: 10px;
}
</style>
